package bsh;

import org.objectweb.asm.MethodVisitor;

import bsh.exception.CompilationFailedException;
import bsh.meta.Scope;
import bsh.meta.TypeWrapper;

/**
 * Compiler para um tipe cast
 * 
 * @author takeshi
 */
public class TypeCastCompiler implements NodeCompiler {

    private final BSHCastExpression node;

    private final CompilationUnit unit;

    /**
     * @param node node
     * @param unit unit
     */
    public TypeCastCompiler(BSHCastExpression node, CompilationUnit unit) {
        super();
        this.node = node;
        this.unit = unit;
    }

    /**
     * {@inheritDoc}
     * 
     * @see bsh.NodeCompiler#compile(org.objectweb.asm.MethodVisitor, bsh.CompilationState)
     */
    public void compile(MethodVisitor host, CompilationState state) throws CompilationFailedException {
        int old = state.getStackSize();
        TypeWrapper toType = this.nodeResultType(state.currentScope());
        this.unit.compileNode(this.node.getChild(1), host, state);
        this.unit.getCompilerManager().coerceStackTopTo(host, toType, state);
        state.assertStackSize(old + 1);
    }

    /**
     * {@inheritDoc}
     */
    public TypeWrapper nodeResultType(Scope scope) throws CompilationFailedException {
        return FormalParameterParser.extractType(this.node.getChild(0), scope);
    }

}
